package com.mcb.autopublish.demos.web.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


/**
 * <p>
 *
 * </p>
 *
 * @author mcb
 * @since 2024/6/7
 */
public final class WeChatVerifyServer {

    // 在微信公众平台后台设置的Token
    private static final String TOKEN = "mcbtoken001";

    // 验证签名
    public static boolean verifySignature(String signature, String timestamp, String nonce) {
        String[] arr = new String[] {TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        String tmpStr = sha1(sb.toString());
        return tmpStr.equals(signature);
    }


    // SHA1加密
    private static String sha1(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] result = digest.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : result) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}
